#!/usr/bin/python
"""
DNSCOMP -- server.py

Dude, your bro is in trouble, and this time it's worse than that Jack Johnson mix CD
I made you being too scratched to play in your Ford F150. You gotta help him out!!!
"""

import socket, sys

IP_LEN = 16

def main():
	try:
		#open a new socket for UDP
		port = int(sys.argv[1]) #the BRO_PORT

		#bind our socket to BRO_PORT
		server_socket.bind( ('', port) )
	except Exception, err:
		sys.stderr.write("There was an error...%s...quitting\n" % err)
		sys.exit(1)

	while True:
		try:
			#receive incoming hostname
			hostname, incoming_address = server_socket.recvfrom(IP_LEN)

			#translate hostname to IP
			ip = socket.gethostbyname(hostname.rstrip())

			#send response
			server_socket.sendto(ip + "\n", incoming_address)
		except Exception, err:
			if err:
				sys.stderr.write("%s" % err)
			return

if __name__ == '__main__':
	server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
	main()
	server_socket.close()
	print "Goodbye!"
